package com.thn.behavior.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thn.behavior.model.UserClickLog;
import com.thn.behavior.service.UserClickLogService;
import com.thn.behavior.mapper.UserClickLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author jzg
* @description 针对表【user_click_log】的数据库操作Service实现
*/
@Slf4j
@Service
public class UserClickLogServiceImpl extends ServiceImpl<UserClickLogMapper, UserClickLog>
    implements UserClickLogService{

    private final RocketMQTemplate rocketMQTemplate;

    // 注入RocketMQTemplate
    public UserClickLogServiceImpl(RocketMQTemplate rocketMQTemplate) {
        this.rocketMQTemplate = rocketMQTemplate;
    }

    public void sendNormalMessage(String topic, String tag, UserClickLog content) {
        // 构建完整目的地（主题:标签）
        String destination = topic + ":" + tag;

        // 创建Spring Messaging Message对象
        Message<UserClickLog> message = MessageBuilder.withPayload(content)
                // 设置业务键（用于追踪）
                .setHeader("ID", "ucl_id_" + content.getId())
                // 定义事件入队列事件
                .setHeader("DATE", new Date().getTime())
                .build();


        /*
        * destination:消息目的地，格式：topic:tags	"ORDER_TOPIC:PAID"
        * payload:消息内容，可以是对象或字符串	order 对象
        * hashKey:用于选择消息队列的哈希键，相同hashKey的消息会被发送到同一队列	"order_1001"
        * timeout:发送超时时间(毫秒)	3000
        * */
        SendResult sendResult = rocketMQTemplate.syncSendOrderly(destination, message, content.getUserId());
        if(sendResult.getSendStatus() == SendStatus.SEND_OK) {
            log.info("普通消息发送成功: {}, 消息ID: {}", destination, sendResult.getMsgId());
        }else {
            log.error("普通消息发送失败: {}, 失败状态: {}", destination, sendResult.getSendStatus());
        }

    }
}




